package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.elite.Util
import cn.com.kh.KHDBConfig
import cn.com.kh.KHUtil
import cn.com.kh.signUtil
import com.alibaba.fastjson.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import cn.com.elite.Util
/**
 * 工单查询API
 */

public class apiWoSend implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiWoSend.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        long startTime = System.currentTimeMillis();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");

        // 初始化返回参数
        JSONObject result = new JSONObject();

        JSONObject resultJson = null;
        //接收客户端调用参数
        String callJson = "";
        InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
        BufferedReader iny = new BufferedReader(reader);
        String line;
        while ((line = iny.readLine()) != null) {
            callJson += line;
        }

        log.info("[调用请求信息]:" + callJson);

        try {
            //解析Json
            JSONObject inJson = JSONObject.parseObject(callJson);

            //获取页面信息参数
            String in_operation_type = inJson.getJSONObject("data").getString("operation_type"); //工单操作类型，保存工单:CLOSE 下送工单：SENDNS 退单：BACK 失败结案：FAILED 工单结案：END 接管未关闭的工单：TAKE 催单：URGE 接管关闭的工单：TAKECL REOPEN：重新打开工单 ROBACK：撤回

            String in_customername = inJson.getJSONObject("data").getString("in_customername"); //基本信息_客户名称
            String in_mobile = inJson.getJSONObject("data").getString("in_mobile"); //基本信息_联系电话
            String in_stalls_code = inJson.getJSONObject("data").getString("in_stalls_code"); //基本信息_档位编号
            String in_accept_acceptor = inJson.getJSONObject("data").getString("in_accept_acceptor"); //受理信息_受理人
            String in_accept_writedate = inJson.getJSONObject("data").getString("in_accept_writedate"); //受理信息_填表日期
            String in_print_flag = inJson.getJSONObject("data").getString("in_print_flag"); //打印标记
            String in_workorder_type = inJson.getJSONObject("data").getString("in_workorder_type"); //工单类型
            String in_elitetask_modifieddate = inJson.getJSONObject("data").getString("in_elitetask_modifieddate"); // 期望解决时间
            String in_elitetask_priority = inJson.getJSONObject("data").getString("in_elitetask_priority"); // 紧急程度
            String in_wo_type = inJson.getJSONObject("data").getString("in_wo_type"); // 处理类型
            String in_workorderflowdetail = inJson.getJSONObject("data").getString("in_workorderflowdetail"); // 工单处理内容描述

            String in_maintask_flag = inJson.getJSONObject("data").getString("in_maintask_flag"); //是否为多任务标记

            String in_wostepcomments = inJson.getJSONObject("data").getString("in_wostepcomments"); // 步骤处理意见
            String in_modifieddate = inJson.getJSONObject("data").getString("in_modifieddate"); // 操作时间
            String in_expireddate = inJson.getJSONObject("data").getString("in_expireddate"); // 工单过期时间
            String in_stepexpired = inJson.getJSONObject("data").getString("in_stepexpired"); // 步骤过期时间
            String in_stepstart = inJson.getJSONObject("data").getString("in_stepstart"); // 步骤开始时间
            String in_cur_expiredlen = inJson.getJSONObject("data").getString("in_cur_expiredlen"); // 当前工单过期时长单位为s
            String in_cur_expiredflag = inJson.getJSONObject("data").getString("in_cur_expiredflag"); // 当前工单是否过期标志 1为已过期 0为未过期
            String in_workstarttime = inJson.getJSONObject("data").getString("in_workstarttime"); // 当前步骤操作开始时间
            String in_workendtime = inJson.getJSONObject("data").getString("in_workendtime"); // 当前步骤操作结束时间

            String in_s_objetive_guid = inJson.getJSONObject("data").getString("in_s_objetive_guid"); //当前objective_guid
            String in_s_elitetask_guid = inJson.getJSONObject("data").getString("in_s_elitetask_guid"); //当前elitetask_guid
            String in_s_customer_guid = inJson.getJSONObject("data").getString("in_s_customer_guid"); //当前customer_guid
            String in_objectivesubstatus= inJson.getJSONObject("data").getString("in_objectivesubstatus"); //当前工单操作状态
            String in_objectivestatus= inJson.getJSONObject("data").getString("in_objectivestatus"); //当前工单状态
            String in_curstepstatus= inJson.getJSONObject("data").getString("in_curstepstatus"); //当前任务状态
            String in_workorder_id= inJson.getJSONObject("data").getString("in_workorder_id"); //工单id
            String in_oldworkerorderguid= inJson.getJSONObject("data").getString("in_oldworkerorderguid"); //关联工单guid
            String in_back_send_type= inJson.getJSONObject("data").getString("in_back_send_type"); //退单下送类型

            String in_s_newcust_flag = inJson.getJSONObject("data").getString("in_s_newcust_flag"); //是否为新客户标记
            String in_r_map_id = inJson.getJSONObject("data").getString("in_r_map_id"); //当前mapid
            String in_r_node_id = inJson.getJSONObject("data").getString("in_r_node_id"); //当前nodeid
            String in_s_userid = inJson.getJSONObject("data").getString("in_s_userid"); //当前staffid
            String in_r_rolegroup_id = inJson.getJSONObject("data").getString("in_r_rolegroup_id"); //当前Rolegroupid
            String in_oldhandlegroup_id = inJson.getJSONObject("data").getString("in_oldhandlegroup_id");// 原处理组
            String in_oldstaff_id = inJson.getJSONObject("data").getString("in_oldstaff_id");// 原处理人
            String in_r_send_group = inJson.getJSONObject("data").getString("in_r_send_group"); //下送至组
            String in_r_send_staff = inJson.getJSONObject("data").getString("in_r_send_staff"); //下送至人
            String in_r_send_node = inJson.getJSONObject("data").getString("in_r_send_node"); //下送至nodeid
            String in_r_back_group = inJson.getJSONObject("data").getString("in_r_back_group"); //退单至组
            String in_r_back_staff = inJson.getJSONObject("data").getString("in_r_back_staff"); //退单至人
            String in_r_back_node = inJson.getJSONObject("data").getString("in_r_back_node"); //退单至节点
            String in_map_roleid = inJson.getJSONObject("data").getString("in_map_roleid"); //当前工单可操作的角色
            String in_auto_sendto = inJson.getJSONObject("data").getString("in_auto_sendto"); //根据档位自动匹配到的组大白菜组id
            String in_auto_send_group = inJson.getJSONObject("data").getString("in_auto_send_group"); //多任务节点存在业务部自动下送至档位匹配到的组别

            String v_fromback_node = '';
            String v_fromback_group = '';
            String v_fromback_staff = '';

            if(in_operation_type == 'BACK')//退单处理逻辑
            {
                in_r_send_node = in_r_back_node;
                in_r_send_group = in_r_back_group;
                in_r_send_staff = in_r_back_staff;
                //退单时默认当前处理角色为客服前台
                in_map_roleid = 'ZCJZVW';

                v_fromback_node = in_r_node_id;
                v_fromback_group = in_r_rolegroup_id;
                v_fromback_staff = in_s_userid;
            };

            String[] data = new String[4];
            //插入步骤信息表
            data[0] = "insert into workorderstep3(workorderstep_guid,workorder_guid,oldhandleby_id,oldhandlegroup_id,handleby_id,handlegroup_id,workorderstepstatus,comments," +
                    "modifieddate,from_stepidmap,to_stepidmap,stepexpired,stepstart,cur_expiredlen,cur_expiredflag,workstarttime,workendtime) " +
                    "values (uuid(), '" + in_s_objetive_guid + "','" + in_oldstaff_id + "','" + in_oldhandlegroup_id + "','" + in_r_send_staff + "','" + in_r_send_group + "','" + in_operation_type + "','" + in_wostepcomments + "','" +
                    in_modifieddate + "','" + in_r_node_id + "','" + in_r_send_node + "','" + in_stepexpired + "','" + in_stepstart + "','" + in_cur_expiredlen + "','" + in_cur_expiredflag + "','" + in_workstarttime + "','" + in_workendtime + "')";
            //插入工单路径数据
            data[1] = "insert into workorderpath3(workorderpath_guid,workorder_guid,handlegroup,handleby,modifieddate,woframe_id,from_stepidmap,to_stepidmap)"+
                    "values (uuid(), '" + in_s_objetive_guid + "','" + in_r_send_group + "','" + in_r_send_staff + "','" + in_modifieddate + "','" + in_r_map_id + "','" + in_r_node_id + "','" + in_r_send_node+"')";
            //更新elitetask
            data[2] = "update elitetask set "+
            "expectendtime = '" + in_elitetask_modifieddate +"',"+
            "handleby_id = '" + in_r_send_staff +"',"+
            "handlegroup_id = '" + in_r_send_group +"',"+
            "modifiedby = '" + in_s_userid +"',"+
            "modifieddate = '" + in_modifieddate +"',"+
            "currentexpectstarttime = '" + in_modifieddate +"',"+
            "comments = '" + in_wostepcomments +"',"+
            "curstepstatus = '" + in_curstepstatus +"',"+
            "flowdetail = '" + in_workorderflowdetail +"',"+
            "objectivesubstatus = '" + in_objectivesubstatus +"',"+
            "curstep_id = '" + in_r_send_node +"',"+
            "curstep_id_map = '" + in_r_send_node +"',"+
            //"maintaskstep_id_map = '" + in_r_node_id +"',"+
            "back_node = '" + v_fromback_node +"',"+
            "back_group = '" + v_fromback_group +"',"+
            "cur_roleid = '" + in_map_roleid +"',"+
            "auto_sendto = case when '" + in_auto_sendto +"' is not null and '" + in_auto_sendto + "' != '' then '" + in_auto_sendto + "' else auto_sendto end,"+
            "back_staff = '" + v_fromback_staff +"'"+
            "where elitetask_guid = '"+ in_s_elitetask_guid + "' and objective_guid = '" + in_s_objetive_guid + "'";
            //更新objective
            data[3] = "update objective set " +
                    "handleby_id = '" + in_r_send_staff +"',"+
                    "handlegroup_id = '" + in_r_send_group +"',"+
                    "expireddate = '" + in_expireddate +"',"+
                    "objectivestatus = '" + in_objectivestatus +"',"+
                    "comments = '" + in_wostepcomments +"',"+
                    "modifiedby = '" + in_s_userid +"',"+
                    "modifieddate = '" + in_modifieddate +"',"+
                    "flowdetail = '" + in_workorderflowdetail +"',"+
                    "curstep_id_map = '" + in_r_send_node +"',"+
                    "objectivesubstatus = '" + in_objectivesubstatus +"' "+
                    "where objective_guid = '" + in_s_objetive_guid + "'";

            log.debug("当前执行更新结果SQL:" + data.toString());
            def dataresult = eliteBean.updateBatch(data, 'dataSource');
            log.debug("当前执行更新结果SQL结果:" + dataresult.toString());

            log.debug("转让工单执行:" + in_r_map_id + " : " + in_objectivesubstatus);
            if(in_r_map_id == 'KHZM6E' && in_objectivesubstatus == 'FEESUR')//如果是转让工单，当前节点是确认收费，则记录objctive确认收费标记
            {
                String updateFeeFlag = "update objective set collect_fee_flag = 'YSF' where objective_guid = '" + in_s_objetive_guid + "'";
                log.debug("执行确认收费标记更新SQL:"+ updateFeeFlag);
                eliteBean.update(updateFeeFlag,'dataSource');
            }

            if(in_maintask_flag=='DRW')//多任务处理逻辑
            {
                String wo_type_code = "";
                String queryWorkOrderSQL = "";
                if(in_r_map_id == 'ZALLDU')
                {
                    //查询装修工单多任务节点 类型标记
                    wo_type_code = 'ZXTASKROLE';
                }else if(in_r_map_id == '1PY9GB')
                {
                    //查询验收工单多任务节点 类型标记
                    wo_type_code = 'YSTASKROLE';
                }

                if((in_r_map_id == "ZALLDU" || in_r_map_id == "1PY9GB") && in_r_node_id == "A4OZLY")
                {
                     queryWorkOrderSQL = "SELECT uuid() as task_guid, n.nodemap_id as task_nod_id, e2.EXTENDVALUE as task_group_id, e3.EXTENDVALUE as task_staff_id," +
                            "awsc.handlegroup_id,awsc.handleby_id,awsc.handletype,n.workorderframe_id as objectivetype_id " +
                            "FROM WO3_node_MAP n " +
                            "LEFT JOIN c_codetables   awsc ON n.map_id = awsc.map_id AND n.nodemap_id = awsc.nodemap_id " +
                            "LEFT JOIN wo3_nodemap_extend   e1 ON n.map_id = e1.map_id AND n.nodemap_id = e1.nodemap_id " +
                            "left join wo3_nodemap_extend   e2 ON e1.nodemap_id = e2.nodemap_id and n.map_id = e2.map_id and e2.EXTENDID = 'TASKGR' " +
                            "left join wo3_nodemap_extend   e3 ON e1.nodemap_id = e3.nodemap_id and n.map_id = e3.map_id and e3.EXTENDID = 'TASKSF' " +
                            "WHERE 1=1 AND e1.EXTENDID = 'MAINTASK' and awsc.use_status = '0' " +
                            "AND e1.extendvalue ='" + in_r_node_id + "'" +
                            "and awsc.code_id ='" + wo_type_code + "'";
                }else
                {
                     queryWorkOrderSQL = "SELECT uuid() as task_guid, n.nodemap_id as task_nod_id, e2.EXTENDVALUE as task_group_id, e3.EXTENDVALUE as task_staff_id," +
                            "awsc.handlegroup_id,awsc.handleby_id,awsc.handletype,n.workorderframe_id as objectivetype_id " +
                            "FROM WO3_node_MAP n " +
                            "LEFT JOIN auto_wo_send_config   awsc ON n.map_id = awsc.map_id AND n.nodemap_id = awsc.nodemap_id " +
                            "LEFT JOIN wo3_nodemap_extend   e1 ON n.map_id = e1.map_id AND n.nodemap_id = e1.nodemap_id " +
                            "left join wo3_nodemap_extend   e2 ON e1.nodemap_id = e2.nodemap_id and n.map_id = e2.map_id and e2.EXTENDID = 'TASKGR' " +
                            "left join wo3_nodemap_extend   e3 ON e1.nodemap_id = e3.nodemap_id and n.map_id = e3.map_id and e3.EXTENDID = 'TASKSF' " +
                            "WHERE 1=1 AND e1.EXTENDID = 'MAINTASK' " +
                            "AND e1.extendvalue ='" + in_r_node_id + "'" +
                            "and n.map_id ='" + in_r_map_id + "'";
                }

                log.debug("执行任务数据查询SQL:" + queryWorkOrderSQL);
                List WorkOrderList = eliteBean.chaxun_sql(queryWorkOrderSQL, "dataSource");
                //获取总行数
                log.debug("执行工单查询数据SQL获取总条数:" + WorkOrderList.size());

                for (int i = 0; i < WorkOrderList.size(); i++) {

                    String task_map_id = in_r_map_id;
                    String staff_role_id = "";
                    Map selectResultcm = WorkOrderList.get(i);
                    String task_nod_id = selectResultcm.get("task_nod_id");
                    String task_group_id = selectResultcm.get("task_group_id");
                    String task_staff_id = selectResultcm.get("task_staff_id");
                    String drw_handlegroup_id = selectResultcm.get("handlegroup_id");
                    String drw_handleby_id = selectResultcm.get("handleby_id");
                    String drw_handletype = selectResultcm.get("handletype");
                    String task_guid = selectResultcm.get("task_guid");
                    String objectivetype_id = selectResultcm.get("objectivetype_id");

                    log.debug("下送节点:" + task_nod_id);
                    log.debug("下送组别:" + task_group_id);
                    log.debug("下送人:" + task_staff_id);

                    if(drw_handletype == 'GR')
                    {
                        staff_role_id = drw_handleby_id;
                    }else if(drw_handletype == 'R')
                    {
                        staff_role_id = drw_handlegroup_id;
                    }else
                    {
                        staff_role_id = "";
                    }

                    if(task_group_id == 'AUTO')
                    {
                        //多任务节点存在业务部自动下送至档位匹配到的组别
                        String queryAutoSendSQL = "select srg.rolegroup_id as rolegroup_id,srg.staff_id as staff_id,sr.role_id as role_id " +
                                "from rolegroup r " +
                                "left join staffrolegroup srg on srg.rolegroup_id = r.rolegroup_id " +
                                "left join staffrole sr on sr.staff_id = srg.staff_id " +
                                "where sr.role_id = '" + staff_role_id + "' and r.dw_rolegroup_id = '" + in_auto_send_group + "'";
                        log.debug("执行任务数据查询SQL:" + queryAutoSendSQL);
                        List AutoSendList = eliteBean.chaxun_sql(queryAutoSendSQL, "dataSource");
                        if(AutoSendList.size()>1)
                        {
                            task_group_id = AutoSendList.get(0).get("rolegroup_id");
                            task_staff_id = "";
                        }else
                        {
                            task_group_id = AutoSendList.get(0).get("rolegroup_id");
                            task_group_id = AutoSendList.get(0).get("staff_id");
                        }
                    }

                    data = new String[2];
                    //插入elitetask
                    data[0] = "insert into elitetask (elitetask_guid,objective_guid,objectivetype_id,expectstarttime,expectendtime,priority,handleby_id,handlegroup_id,createdby,createddate,modifiedby,modifieddate,currentexpectstarttime,comments,customer_guid,curstepstatus,curstep_id,flowdetail,curstep_id_map,map_id,objectivesubstatus,cur_roleid,auto_sendto,obflag,maintaskstep_id_map,back_node,back_group,back_staff) " +
                            "values( '" + task_guid + "','" + in_s_objetive_guid + "','" + objectivetype_id + "','" + in_modifieddate + "','" + in_elitetask_modifieddate + "','NORMAL','" + task_staff_id +  "','" + task_group_id + "','" + in_s_userid + "','" + in_modifieddate + "','" + in_s_userid + "','" + in_modifieddate + "','" + in_modifieddate + "','" + in_wostepcomments + "','" + in_s_customer_guid + "','" + in_curstepstatus + "','" + task_nod_id + "','" +  in_workorderflowdetail + "','" + task_nod_id + "','" + task_map_id + "','" + in_objectivesubstatus + "','" + staff_role_id + "','" + in_auto_sendto + "','0',null,null,null,null)";
                    //插入工单路径数据
                    data[1] = "insert into workorderpath3(workorderpath_guid,workorder_guid,handlegroup,handleby,modifieddate,woframe_id,from_stepidmap,to_stepidmap)"+
                            "values (uuid(), '" + in_s_objetive_guid + "','" + task_group_id + "','" + task_staff_id + "','" + in_modifieddate + "','" + task_map_id + "','" + in_r_node_id + "','" + task_nod_id+"')";
                    log.debug("当前执行更新结果SQL:" + data.toString());
                     dataresult = eliteBean.updateBatch(data, 'dataSource');
                    log.debug("当前执行更新结果SQL结果:" + dataresult.toString());

                    //调用短信发送接口发送短信
                    String post_body = '''{"data":{"in_r_objectivesubstatus":"''' + in_objectivesubstatus + '''",''' +
                        '''"in_map_roleid":"''' + staff_role_id + '''",''' +
                        '''"in_r_remark":"",''' +
                        '''"in_s_objetive_guid":"''' + in_s_objetive_guid + '''",''' +
                        '''"in_s_elitetask_guid":"''' + task_guid + '''",''' +
                        '''"in_r_map_id":"''' + in_r_map_id + '''",''' +
                        '''"in_r_node_id":"''' + in_r_node_id + '''"}}'''

                    String woMessageURL = KHDBConfig.getAPIURL(eliteBean, "NGS-Local") + "/ngsapitask/api/apiWoMessageEntrance";
                    String woMessageResult = Util.doHttpPost(woMessageURL, post_body, "UTF-8", 5000, 0);
                    JSONObject woMessageJson = JSONObject.parseObject(woMessageResult);
                    String re_code = woMessageJson.getString("code");
                }
            }

            long endTime = System.currentTimeMillis();
            result.put("code", 1);
            result.put("msg", "处理完成、调用问题处理时长(毫秒):" + (endTime - startTime));

        } catch (Exception e) {
            result.put("code", 1008);
            result.put("msg", e.getMessage());
        }

        return result.toString();

    }
}